package com.threefivework.mymall.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * descripiton:
 *
 * @author: kinson(2219945910@qq.com)
 * @date: 2018/6/27
 * @time: 7:51
 * @modifier:
 * @since:
 */
@Aspect
@Component
@Order(1)
public class MyMallAspect {

    private static final Logger logger = LoggerFactory.getLogger(MyMallAspect.class);

    private ThreadLocal<Long> threadLocal = new ThreadLocal<Long>();

    @Pointcut("execution(public * com.threefivework.mymall.controller.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        threadLocal.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("==============URL=============={}", request.getRequestURL().toString());
        logger.info("==============HTTP_METHOD=============={}", request.getMethod());
        logger.info("==============IP=============={}", request.getRemoteAddr());
        logger.info("==============CLASS_METHOD=============={}", joinPoint.getSignature().getDeclaringTypeName()
                + "." + joinPoint.getSignature().getName());
        logger.info("==============ARGS=============={}", Arrays.toString(joinPoint.getArgs()));
        logger.info("==============URL=============={}", request.getRequestURL().toString());
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("============方法的返回值============{}", ret);
    }

    @AfterThrowing("webLog()")
    public void afterThrowing(){
        logger.error("============方法执行完异常============");
    }

    @After("webLog()")
    public void after(JoinPoint point) {
        logger.info("============请求完毕，共耗时============={}", (System.currentTimeMillis() - threadLocal.get()) + "ms");
    }

    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjd) {
        logger.info("==========环绕开始=========");
        try {
            Object object = pjd.proceed();
            logger.info("========方法环绕结果为========{}", object);
            return object;
        } catch (Throwable throwable) {
            logger.error("=======异常======={}", throwable);
            return null;
        }
    }

}
